<template>
    <div>
        <!-- 上方返回栏 -->
        <el-row>
            <el-col :span="24"><div class="grid-content bg-purple-dark">
                <el-page-header @back="goBack" content="文章详情"></el-page-header>
            </div></el-col>
        </el-row>
        <!-- 背景盒子 -->
        <div class="background">
            <!-- 文章盒子 -->
			<el-card class="article">

                <h1 style="text-align: center;">{{this.article.title}}</h1><br>
                <!-- 文章内容盒子 -->
                <div v-if="article.content">
                    <div v-html="this.article.content"></div>
                </div>

                <br>
                <br>
                <div style="direction: rtl;display: flex;">
                <div class="icon-box">
                   <i class="el-icon-star-off" @click="handleCollect" />
                   <span>{{collectedCount}}</span>
                </div>
                
                <div class="icon-box">
                   <i class="el-icon-thumb" @click="handlePraise"/>
                   <span>{{praiseCouunt}}</span>
                </div>
                <div class="icon-box">
                   <i class="el-icon-chat-line-square"/>
                   <span>{{commentCount}}</span>
                </div>
            </div>
                <el-divider></el-divider>

                <!-- 评论区盒子 -->
                <div class="comments">
                    <h3>评论</h3>
                    <!-- 用户评论盒子 -->
                    <div class="commentInput">
                        <el-avatar size="60" @error="errorHandler">
                            <img :src="userInfo.avatar"/>
                        </el-avatar>
                        <el-input :autosize="{ minRows: 2, maxRows: 4}" class="input" type="textarea" v-model="commentText" placeholder="哎呦，不错哦，发条评论吧"></el-input>
                        <el-button class="sumbit" type="primary"  @click="publish">发布</el-button>
                    </div><br>
                    <div v-for="comment in commentList" :key="comment.userId">
                        <!-- 评论盒子 -->
                        <div class="commentBox">
                            <el-avatar :size="60" @error="errorHandler">
                                <img :src="comment.avatar"/>
                            </el-avatar>
                            <p class="nickName">{{comment.nickName}}</p>
                            <p class="commentText">{{comment.commentText}}</p>
                            <p class="createDate">{{comment.createDate}}</p>
                        </div>
                    </div>

                </div>
            </el-card>
        </div>
    </div>
</template>

<script>
import { getArticleById} from '../api/article';
import { submitComment,getCommentListById,getCommentCount } from '../api/comment';
import{getBaseUserInfo} from '../api/userInfo'
import {getPraiseCount,getCollectedCount,praise,collect,isCollected,isPraised} from '../api/common'

export default {
    name:"article-component",
    data(){
        return{
            ArticleId:this.$route.query.id,
            commentText:'',
            article:{
                title:'',
                content:'',
                createDate:'',
                updateTime:'',
                userId:''
            },
            commentList:[],
            userInfo:{
                avatar:'',
                nickName:'',
            },
            commentCount:0,
            praiseCouunt:0,
            collectedCount:0,

        }
    },
    created() {
        this.fetchArticle();
        this.fetchUserInfo();
        this.fetchCommentList();

    },
    mounted:function(){
        this.fetchCollectedCount();
        this.fetchCommentCount();
        this.fetchPraiseCount();
    },
    methods: {
        fetchCommentCount(){
            getCommentCount({
            'articleId':this.ArticleId
        }).then(res => {
            if (res.code == 1)
                this.commentCount = res.data;
            else this.$message.error("获取评论数失败")
        })
        },
        fetchPraiseCount(){
            getPraiseCount({
            'articleId':this.ArticleId
        }).then(res => {
            if (res.code == 1)
                this.praiseCouunt = res.data;
            else this.$message.error("获取点赞数失败")
        })
        },
        fetchCollectedCount(){
            getCollectedCount({
                'articleId':this.ArticleId
            }).then(res => {
                if (res.code == 1)
                    this.collectedCount = res.data;
                else this.$message.error("获取收藏数失败")
            })
        },
        handlePraise(){
            isPraised({
                'articleId':this.ArticleId
            }).then(res =>{
                if (res.code == 1){
                    if (res.data == 1){
                        this.$message.warning("已经点赞过")
                        return;
                    }else {
                        praise({
                            'articleId':this.ArticleId
                        })
                        this.fetchPraiseCount();
                    }
                }else this.$message.error("出现错误")
            })
        },
        handleCollect(){
            isCollected({
                'articleId':this.ArticleId
            }).then (res =>{
                if (res.code == 1){
                    if (res.data == 1){
                        this.$message.warning("已经收藏过")
                        return;
                    }else{
                        collect({
                            'articleId':this.ArticleId
                        })
                        this.fetchCollectedCount();
                    }
                }else this.$message.error("出现错误")
            })
        },
        //获取后端数据（文章
        async fetchArticle(){
            try{
                const response = await getArticleById(this.ArticleId);
                this.article=response.data;
            }catch(error){
                console.error('Error fetching articles:', error);
            }
        },
        //获取文章对应的评论
        async fetchCommentList(){
            try {
                const response = await getCommentListById(this.ArticleId);
                this.commentList=response.data;
                //循环遍历评论列表，获取每个评论的用户信息
                // for(let i=0;i<this.commentList.length;i++){
                //     const userId = this.commentList[i].userId;
                //     const userInfoResponse = await getUserInfoById(userId);
                //     this.comments.push({
                //         'nickName': userInfoResponse.data.nickName,
                //         'avatar': userInfoResponse.data.avatar,
                //         'commentText': this.commentList[i].commentText,
                //         'createDate': this.commentList[i].createDate,
                //         'id':this.commentList[i].id
                //     })
                // }
            } catch (error) {
                console.log('Error fetching commentList',error);
            }
        },
        //获取当前用户的昵称和头像
        async fetchUserInfo(){
            try {
                const response = await getBaseUserInfo();
                this.userInfo.avatar=response.data.avatar;
                this.userInfo.nickName=response.data.nickName;
            } catch (error) {
                console.log('Error fetching userInfo',error);
            }
        },
		//返回文章列表
        goBack() {
            this.$router.push('/articles');
        	console.log('go back');
      	},
		// 获取当前时间的函数	
    	getCurrentTime() {
    	    var now = new Date();
        	var year = now.getFullYear();
        	var month = ('0' + (now.getMonth() + 1)).slice(-2);
        	var day = ('0' + now.getDate()).slice(-2);
        	// var hours = ('0' + now.getHours()).slice(-2);
        	// var minutes = ('0' + now.getMinutes()).slice(-2);
        	// var seconds = ('0' + now.getSeconds()).slice(-2);
        	// return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
            return year + '-' + month + '-' + day;
    	},
        //提交评论
        async publish(){
            if(this.commentText.trim()==''){
                this.$message.error('评论内容不能为空');
                return;
            }
            const comment={
                commentText:this.commentText,
                createDate:this.getCurrentTime(),
                articleId:this.ArticleId,
            }
            
            await submitComment({
                'commentText':this.commentText,
                'createDate':this.getCurrentTime(),
                'articleId':this.ArticleId,
            });

            comment.userImg=this.userInfo.userImg;
            comment.nickName=this.userInfo.nickName;
            if(comment.nickName==''||comment.nickName==null)
            {
                comment.nickName="匿名用户";
            }
            //清空评论框
            this.commentText='';
            this.$message.success('评论成功');
            // 将新评论添加到评论列表
            this.fetchCommentList()
            this.fetchCommentCount();
        },
        errorHandler() {
            return true
        },
    },
			

}
</script>

<style>
.icon-box{
    display: inline;
    width: 20px;
    margin-left: 40px;
    justify-content: center;
    align-items: center;
    text-align: center;
}
.icon-box>i{
    display: block;
    font-size: 25px;
}
.el-row {
    margin-bottom: 0px;
    background:rgb(59,93,130);
  }
  .el-col {
    border-radius: 10px;
  }
  .el-page-header{
    padding: 10px;
    display: flex;
    line-height: 30px;
  }
  .background{
    margin: 0;
    padding: 0;
    background-image: url(https://tse2-mm.cn.bing.net/th/id/OIP-C.rzuj-lOyTbi1bgBP-rHK1AHaEB?w=305&h=180&c=7&r=0&o=5&dpr=1.3&pid=1.7); 
    background-size: cover; 
    background-position: center; 
    align-items: center;
    justify-content: center;
    display: flex;
  }
    .background .article{
      width: 80%;
      margin: 10px;
      border: 1px;
      padding: 13px;
      background: white;
      line-height: 2;
      font-size: 18px;
      color: rgb(24,25,28);
    }
    .commentInput .input{
        width: 85%;
        position: relative;
        left: 10px;
        top:-13px;
    }
    .commentInput .sumbit{
        position: relative;
        left: 20px;
        top:-13px;
        height: 52px;
        width:100px;
    }
    .commentBox .nickName{
        font-size: 13px;
        color: rgb(158,112,109);
        position: relative;
        left: 70px;
        top: -75px;
    }
    .commentBox .commentText{
        color: rgb(24,25,28);
        position: relative;
        left: 70px;
        top: -75px;
    }
    .commentBox .createDate{
        font-size: 12px;
        color: rgb(148,156,163);
        position: relative;
        left: 70px;
        top: -75px;
    }
        
    


</style>